package org.jeecg.modules.pos.controller;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.modules.pos.PosBookingStateEnum;
import org.jeecg.modules.pos.entity.*;
import org.jeecg.modules.pos.service.*;
import org.jeecg.modules.pos.vo.PosBooingOrderGoods;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description: pos_order_goods
 * @Author: jeecg-boot
 * @Date:   2023-04-13
 * @Version: V1.0
 */
@Api(tags="pos_order_goods")
@RestController
@RequestMapping("/pos/posOrderGoods")
@Slf4j
public class PosOrderGoodsController extends JeecgController<PosOrderGoods, IPosOrderGoodsService> {
	@Autowired
	private IPosBookingService bookingService;
	@Autowired
	private IPosOrderGoodsDetailService posOrderGoodsDetailService;
	@Autowired
	private IPosTypeService posTypeService;
	@Autowired
	private IPosOrderGoodsPaymentService posOrderGoodsPaymentService;
	/**
	 * 分页列表查询
	 */
	//@AutoLog(value = "pos_order_goods-分页列表查询")
	@ApiOperation(value="pos_order_goods-分页列表查询", notes="pos_order_goods-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<PosOrderGoods>> queryPageList(PosOrderGoods posOrderGoods,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<PosOrderGoods> queryWrapper = QueryGenerator.initQueryWrapper(posOrderGoods, req.getParameterMap());
		Page<PosOrderGoods> page = new Page<PosOrderGoods>(pageNo, pageSize);
		IPage<PosOrderGoods> pageList = service.page(page, queryWrapper);
		pageList.getRecords().forEach(item -> {
			PosType posType = posTypeService.getById(item.getPosType());
			if(posType!=null) {
				item.setPosTypeName(posType.getName());
			}
		});
		return Result.OK(pageList);
	}


	 /**
	  *   添加
	  */
	 @AutoLog(value = "pos_order_goods-添加")
	 @ApiOperation(value="pos_order_goods-添加", notes="pos_order_goods-添加")
	 //@RequiresPermissions("pos:pos_order_goods:add")
	 @PostMapping(value = "/add")
	 public Result<PosOrderGoods> add(@RequestBody PosOrderGoods posOrderGoods) {
		 // 如果是取单，不添加新商品，然后直接结算时PosOrderGoodsDetailList为空
//		 if (ObjectUtils.isEmpty(posOrderGoods.getPosOrderGoodsDetailList())) {
//			 return Result.error("请先选择商品");
//		 }
		 PosOrderGoods orderGoods = service.addOrder(posOrderGoods);
		 return Result.OK("添加成功", orderGoods);
	 }

	 /**
	  *   添加预约单
	  */
	 @AutoLog(value = "pos_booking_order-添加预约单")
	 @ApiOperation(value="pos_booking_order-添加预约单", notes="pos_booking_order-添加预约单")
	 //@RequiresPermissions("pos:pos_order_goods:add")
	 @Transactional(rollbackFor = Exception.class)
	 @PostMapping(value = "/addBooking")
	 public Result<Boolean> addBooking(@RequestBody PosBookingOrder bookingOrder) {
		 return Result.OK("添加成功", service.addBookingOrder(bookingOrder));
	 }

	 /**
	  *   修改预约单
	  */
	 @AutoLog(value = "pos_booking_order-修改预约单")
	 @ApiOperation(value="pos_booking_order-修改预约单", notes="pos_booking_order-修改预约单")
	 //@RequiresPermissions("pos:pos_order_goods:add")
	 @Transactional(rollbackFor = Exception.class)
	 @PostMapping(value = "/editBooking")
	 public Result<Boolean> editBooking(@RequestBody PosBookingOrder bookingOrder) {
		 return Result.OK("修改成功", service.editBookingOrder(bookingOrder));
	 }

	 /**
	  *   根据预约单id查询预约单详情
	  */
	 @AutoLog(value = "pos_booking_order-根据预约单id查询预约单详情")
	 @ApiOperation(value="pos_booking_order-根据预约单id查询预约单详情", notes="pos_booking_order-根据预约单id查询预约单详情")
	 //@RequiresPermissions("pos:pos_order_goods:add")
	 @Transactional(rollbackFor = Exception.class)
	 @GetMapping(value = "/getBookingOrderById")
	 public Result<PosBookingOrder> getBookingOrderById(String bookingId) {
		 return Result.OK(service.getBookingOrderById(bookingId));
	 }

	 /**
	  *   分页查询预约单
	  */
	 @AutoLog(value = "pos_booking_order-分页查询")
	 @ApiOperation(value="pos_booking_order-分页查询", notes="pos_booking_order-分页查询")
	 //@RequiresPermissions("pos:pos_order_goods:add")
	 @GetMapping(value = "/getBookingPage")
	 public Result<Page<PosBooingOrderGoods>> getBookingPage(PosBookingOrder bookingOrder,
								@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								@RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
							   @RequestParam(name="startTime" ,required=false) @JsonFormat(pattern = "yyyy-MM-dd")  @DateTimeFormat(pattern="yyyy-MM-dd") DateTime startTime,
							   @RequestParam(name="endTime" ,required=false) @JsonFormat(pattern = "yyyy-MM-dd")  @DateTimeFormat(pattern="yyyy-MM-dd") DateTime endTime) {
		 Page<PosBooingOrderGoods> page = new Page<>(pageNo, pageSize);
//		 Page<PosBookingOrder> bookingOrderPage = bookingService.getBookingPage(bookingOrder,page,startTime,endTime);
//		 List<String> codes = bookingOrderPage.getRecords().stream().map(PosBookingOrder::getCode).collect(Collectors.toList());
//		 List<PosOrderGoods> orderGoodsList = service.list(Wrappers.<PosOrderGoods>lambdaQuery().in(PosOrderGoods::getBookingCode, codes));
//		 bookingOrderPage.getRecords().forEach(e -> {
//			 List<PosOrderGoods> posOrderGoods = orderGoodsList.stream().filter(ele -> StrUtil.equals(ele.getBookingCode(), e.getCode())).collect(Collectors.toList());
//			 e.setPosOrderGoodList(posOrderGoods);
//		 });


		 Page<PosBooingOrderGoods> bookingOrderPage = service.getBookingOrderPage(bookingOrder, page, startTime, endTime);

		 return Result.OK(bookingOrderPage);
	 }


	 /**
	  *   根据桌号查询今日预约单
	  */
	 @AutoLog(value = "pos_booking_order-根据桌号查询今日预约单")
	 @ApiOperation(value="pos_booking_order-根据桌号查询今日预约单", notes="pos_booking_order-根据桌号查询今日预约单")
	 @GetMapping(value = "/getBookingByTableId")
	 public Result<List<PosBookingOrder>> getBookingByTableId(String tableId) {
		 if (tableId == null || tableId.isEmpty()){
			 return Result.error("请选择桌台");
		 }
		 return Result.OK(service.getBookingByTableId(tableId));
	 }

	 /**
	  *   预定开台
	  */
	 @AutoLog(value = "预定开台")
	 @ApiOperation(value="预定开台", notes="预定开台")
	 @Transactional(rollbackFor = Exception.class)
	 @GetMapping(value = "/addOrderByBookingId")
	 public Result<Boolean> addOrderByBookingId(String bookingId) {
		 if (bookingId == null || bookingId.isEmpty()){
			 return Result.error("请选择预约单");
		 }
		 return Result.OK(service.addOrderByBookingId(bookingId));
	 }

	 /**
	  *   预约单退订
	  */
	 @AutoLog(value = "预约单退订")
	 @ApiOperation(value="预约单退订", notes="预约单退订")
	 @Transactional(rollbackFor = Exception.class)
	 @GetMapping(value = "/removeBooking")
	 public Result<Boolean> cancelBooking(PosBookingOrder bookingOrder) {
		 return Result.OK(service.cancelBooking(bookingOrder));
	 }

	 /**
	  *   预约单逾期
	  */
	 @AutoLog(value = "预约单逾期")
	 @ApiOperation(value="预约单逾期", notes="预约单逾期")
	 @Transactional(rollbackFor = Exception.class)
	 @GetMapping(value = "/overTimeBooking")
	 public Result<Boolean> overTimeBooking(String bookingOrderId) {
		 PosBookingOrder bookingOrder = bookingService.getById(bookingOrderId);
		 if (!PosBookingStateEnum.NO_ARRIVE.getKey().equals(bookingOrder.getState())){
			 return Result.error("未到店订单时才能逾期");
		 }
		 bookingOrder.setState(PosBookingStateEnum.OVER_TIME.getKey());
		 return Result.OK(bookingService.updateById(bookingOrder));
	 }

	 /**
	  * 台桌时挂房账
	  */
	 @AutoLog(value = "pos_order_goods-挂房账")
	 @ApiOperation(value="pos_order_goods-挂房账", notes="pos_order_goods-挂房账")
	 @Transactional(rollbackFor = Exception.class)
	 @PostMapping("/addRoomFee")
	 public Result<Boolean> addRoomFee(@RequestBody PosOrderGoods posOrderGoods,String hotelId){
		 return Result.ok(service.addRoomFee(posOrderGoods, hotelId));
	 }

	 @ApiOperation(value="getOrderByTableId", notes="getOrderByTableId")
	 @GetMapping(value = "/getOrderByTableId")
	 public Result<PosOrderGoods> getOrderByTableId(String tableId) {
		 return Result.ok(service.getOrderByTableId(tableId));
	 }

	 /**
	  * 撤销结账
	  */
	 @AutoLog(value = "cancelSettle")
	 @ApiOperation(value="cancelSettle", notes="cancelSettle")
	 @RequestMapping(value = "/cancelSettle", method = {RequestMethod.PUT,RequestMethod.POST})
	 public Result<String> cancelSettle(@RequestParam(name="code",required=true) String code) {
		 LambdaUpdateWrapper<PosOrderGoods> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
		 lambdaUpdateWrapper.eq(PosOrderGoods::getCode, code);
		 lambdaUpdateWrapper.set(PosOrderGoods::getStatus, 0);
		 lambdaUpdateWrapper.set(PosOrderGoods::getPayInfo, "");
		 service.update(lambdaUpdateWrapper);

		 LambdaQueryWrapper<PosOrderGoodsPayment> LambdaQueryWrapper = new LambdaQueryWrapper<>();
		 LambdaQueryWrapper.eq(PosOrderGoodsPayment::getOrderId, code);
		 posOrderGoodsPaymentService.remove(LambdaQueryWrapper);
		 return Result.OK("撤销成功!");
	 }

	 /**
	  *   通过code删除
	  *
	  */
	 @AutoLog(value = "pos_order_goods-通过id删除")
	 @ApiOperation(value="pos_order_goods-通过id删除", notes="pos_order_goods-通过id删除")
	 //@RequiresPermissions("pos:pos_order_goods:delete")
	 @DeleteMapping(value = "/deleteOrder")
	 public Result<String> deleteOrder(@RequestParam(name="code",required=true) String code) {
		 LambdaQueryWrapper<PosOrderGoods> LambdaQueryWrapper = new LambdaQueryWrapper<>();
		 LambdaQueryWrapper.eq(PosOrderGoods::getCode, code);
		 service.remove(LambdaQueryWrapper);

		 LambdaQueryWrapper<PosOrderGoodsDetail> LambdaQueryWrapper2 = new LambdaQueryWrapper<>();
		 LambdaQueryWrapper2.eq(PosOrderGoodsDetail::getOrderId, code);
		 posOrderGoodsDetailService.remove(LambdaQueryWrapper2);

		 return Result.OK("删除成功!");
	 }


	/**
	 *  编辑
	 */
	@AutoLog(value = "pos_order_goods-编辑")
	@ApiOperation(value="pos_order_goods-编辑", notes="pos_order_goods-编辑")
	//@RequiresPermissions("pos:pos_order_goods:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody PosOrderGoods posOrderGoods) {
		service.updateById(posOrderGoods);
		return Result.OK("编辑成功!");
	}

	/**
	 *   通过id删除
	 */
	@AutoLog(value = "pos_order_goods-通过id删除")
	@ApiOperation(value="pos_order_goods-通过id删除", notes="pos_order_goods-通过id删除")
	//@RequiresPermissions("pos:pos_order_goods:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		service.removeById(id);
		return Result.OK("删除成功!");
	}

	/**
	 *  批量删除
	 */
	@AutoLog(value = "pos_order_goods-批量删除")
	@ApiOperation(value="pos_order_goods-批量删除", notes="pos_order_goods-批量删除")
	//@RequiresPermissions("pos:pos_order_goods:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		service.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

	/**
	 * 通过id查询
	 */
	//@AutoLog(value = "pos_order_goods-通过id查询")
	@ApiOperation(value="pos_order_goods-通过id查询", notes="pos_order_goods-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<PosOrderGoods> queryById(@RequestParam(name="id",required=true) String id) {
		PosOrderGoods posOrderGoods = service.getById(id);
		if(posOrderGoods==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(posOrderGoods);
	}

	 /**
	  * 联台
	  */
	 @ApiOperation(value="联台", notes="联台")
	 @Transactional(rollbackFor = Exception.class)
	 @RequestMapping(value = "/merge-order",method = RequestMethod.POST)
	 public Result<Boolean> mergePosOrder(String hotelId, String mainPosOrderId,@RequestBody List<String> posOrderIds){
		 return  Result.OK(service.mergePosOrder(hotelId,mainPosOrderId,posOrderIds));
	 }

	 /**
	  * 取消联台
	  */
	 @ApiOperation(value="取消联台", notes="取消联台")
	 @Transactional(rollbackFor = Exception.class)
	 @RequestMapping(value = "/return-merge-order",method = RequestMethod.GET)
	 public Result<Boolean> returnMergePosOrder(String posOrderId){
		 return  Result.OK(service.returnMergePosOrder(posOrderId));
	 }

	 /**
	  * 换桌
	  */
	 @ApiOperation(value="换桌", notes="换桌")
	 @Transactional(rollbackFor = Exception.class)
	 @RequestMapping(value = "/change-table",method = RequestMethod.GET)
	 public Result<Boolean> changeTable(String posOrderId,String tableId ){
		 return  Result.OK(service.changeTable(posOrderId,tableId));
	 }



	 /**
	  * 转菜
	  */
	 @ApiOperation(value="转菜", notes="转菜")
	 @Transactional(rollbackFor = Exception.class)
	 @RequestMapping(value = "/transfer-dishes",method = RequestMethod.POST)
	 public Result<Boolean> transferDishes(String posOrderId,@RequestBody List<String> orderGoodsDetailIds ){
		 return  Result.OK(service.transferDishes(posOrderId,orderGoodsDetailIds));
	 }

    /**
    * 导出excel
    */
    //@RequiresPermissions("pos:pos_order_goods:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, PosOrderGoods posOrderGoods) {
        return super.exportXls(request, posOrderGoods, PosOrderGoods.class, "pos_order_goods");
    }

    /**
      * 通过excel导入数据
    */
    //@RequiresPermissions("pos:pos_order_goods:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, PosOrderGoods.class);
    }

}
